const config = require('../config');
const { postImg } = require('../model/postImg')
const OSS = require('ali-oss')
exports.uploadFile = async (req, res, next) => {
    try {
        // let topicId = req.params.id
        let userId = req.userData._id
        let client = new OSS({
            region: "oss-cn-shenzhen",
            accessKeyId: "LTAI5t6AAp8oTfAzmVdwDWWq",
            accessKeySecret: "1TgAN3aEWr3cSRFO9OrSUr3e7feyST",
            bucket:"bs2022-storage"
        });
        //存储网址
        const endPoint = 'bs2022-storage.oss-cn-shenzhen.aliyuncs.com'
        //存储的OSS链接库
        const bucket = 'bs2022-storage';
        await client.useBucket(bucket)
        console.log(req.file.path)
        let putResult =await client.put('/uploads/'+ req.file.filename,req.file.path,{
            headers: {
                'Content-Type': 'image/jpg',
                "Content-Disposition":"inline"
            }
        })

        let uploadImageSrc = `http://${endPoint}/` + putResult.name
        const topicImages = new postImg({ 
            // url: `/uploads/${req.userData._id}/` + req.file.filename,
            url:putResult.name,
            name:req.file.filename ,
            // topic: topicId
            user:userId
        })
        await topicImages.save()
        // req.uploadImages=topicImages._id
        res.status(200).json({
            errno: 0,
            code: 200,
            msg: '文件上传成功',
            data: {
                // url: `${config.server}:${config.app.port}` + `/uploads/${req.userData._id}/` + req.file.filename,
                url:uploadImageSrc,
                // url:"http://"+bucket+"."+endPoint+"/uploads/"+req.file.filename,
                alt: req.file.filename,                                 
            }
        })
    } catch (err) {
        next(err)
    }
}

 